<template>
  <div class="orderTableList">
    <el-card class="box-card"
             shadow="never">
      <!-- 订单查询 -->
      <UserSearch @search="reload"></UserSearch>
      <ele-pro-table ref="table"
                     :columns="columns"
                     :datasource="datasource"
                     :border="false"
                     :disabled="false"
                     :toolbar="false"
                     class="customStyle"
                     default-expand-all
                     cache-key="systemUserTable">
        <!-- 展开内容 -->
        <template v-slot:expand="{ row }">
          <div class="orderrowinfo">
            <span class="orderNumber"> 订单号:{{ row?.sn_order }}</span>

            <span class="createDate">
              创建时间:{{ toDateString(row?.create_time) }}</span>

            <span class="buyName">
              购买用户:{{ row?.nickname? row?.nickname :'--' }}</span>
            <span class="iphone">
              买家手机号:{{ row?.phone? row?.phone:'--'  }}</span>
          </div>
        </template>
        <!-- Number(item.packageList?.servicePrice)+ -->
        <template v-slot:servicePrice="{ row }">
          <div v-if="row.orderList?.length">
            <div>
              <!-- +Number(row.packageList?.servicePrice) -->
              ￥{{(overtimePrice(row.packageList?.servicePrice, row.orderList ))}}元
            </div>
            <!-- <div>
              ￥{{Number(row.packageList?.servicePrice) }}元
            </div> -->
          </div>
          <div v-else-if="(!(row.orderList?.length)&&row?.fatherOrderNumber)">
            ￥{{ row.packageList?.plusClockPrice }}元
          </div>
          <div v-else>
            ￥{{ row.packageList?.servicePrice }}元
          </div>
        </template>
        <template v-slot:serviceCategoriesId="{ row }">
          <div style="z-index: 999999999;">
            {{ row.serviceCategories?.classificationName }}
          </div>
        </template>
        <!-- 订单信息 -->
        <template v-slot:orderingInformation="{ row }">
          <div class="realNameStyle flex-between">

            <img class="avaterName "
                 :src="row.host_img[0]"
                 alt="" />
            <div class="technicianName font-overflow2">{{ row.goods_name }}</div>

          </div>
        </template>
        <!-- 信息 -->
        <template v-slot:informations="{ row }">

          <div class="flex-column">
            <el-link :underline="false"
                     :type="informationType(row.status)?.types">
              订单状态： {{ informationType(row.status).text }}
            </el-link>

            <!-- <el-link :underline="false">
              {{ row.payStatus}}
            </el-link> -->
            <el-link :underline="false"
                     type="primary"
                     @click="divDetail(row)">
              查看详情
            </el-link>

            <!-- <el-link :underline="false"
                     class="technicianName"
                     @click="visibleModalFn(row)"
                     v-if="row.status == 1 && Number(timestamps(row.createdAt)) - currTime <= 0"><span style="color: red;">取消订单</span></el-link> -->
          </div>

        </template>

        <template v-slot:total_price="{ row }">

          <div>
            <div>
              原价<span> {{ row.total_price}}</span>

            </div>
            <div>
              已优惠:{{Number(row.total_price)?(Number(row.total_price)-Number(row.reality_amount)).toFixed(2):0}}元

            </div>
          </div>

        </template>
        <template v-slot:take_over_way="{ row }">
          <el-link :underline="false"
                   :type="success">
            {{row.take_over_way==1?'自提':'送货上门' }}
          </el-link>
        </template>
        <template v-slot:pay_way="{ row }">
          <el-link :underline="false"
                   :type="serviceStatusType(row.pay_way)?.types">
            {{ serviceStatusType(row.pay_way).text }}
          </el-link>
        </template>
        <!-- <template v-slot:pay_way="{ row }">
         
          <el-link :underline="false"
                   :type="row.pay_way=='1'?'warning':'success'">
            {{ row.pay_way=='1'?'余额支付':'微信支付' }}
          </el-link>
        </template> -->

        <!-- 操作 -->
        <template v-slot:action="{ row }">
          <el-link v-if="row.status==3"
                   type="primary"
                   :underline="false"
                   icon="el-icon-edit"
                   @click="openEdit(row)">
            修改地址
          </el-link>

          <el-link v-if="row.status==3"
                   type="danger"
                   @click="remove(row)"
                   :underline="false"
                   icon="el-icon-shopping-bag-2">
            立即发货
          </el-link>
          <el-link type="primary"
                   v-if="row.status==6"
                   :underline="false"
                   icon="el-icon-edit"
                   @click="openPrintList(row)">
            选择打印机
          </el-link>
          <!-- <el-popconfirm @confirm="agreeRefund(row)"
                         title="是否同意退款？？">
            <el-button slot="reference"
                       v-show="row.status==5">同意退款</el-button>
          </el-popconfirm> -->
          <el-popconfirm class="ele-action"
                         title="是否同意退款？"
                         @confirm="agreeRefund(row)">

            <el-link slot="reference"
                     type="primary"
                     v-show="row.status==5"
                     :underline="false"
                     icon="el-icon-edit">
              同意退款
            </el-link>

          </el-popconfirm>
        </template>

      </ele-pro-table>
    </el-card>

    <drawerOrderInfo :data="current"
                     :drawerOrderInfo.sync="drawerEditBoolen"></drawerOrderInfo>
    <ele-modal width="600px"
               height="300px"
               title="发货"
               :visible.sync="visibleModalDelivery"
               :maxable="true">
      <!-- class="SigningReminder" -->

      <div class="flex-between padding_20rpx_0 m-bottom15"
           style="border-bottom: 2rpx solid rgb(230, 230, 230);">
        <div class="">
          <el-input class="uni-input"
                    v-model="logisticsForm.express_name"
                    placeholder="填写送货人姓名"></el-input>
        </div>

      </div>

      <div class="flex-between padding_30rpx_0"
           style="border-bottom: 2px solid rgb(230, 230, 230);">
        <!-- <pca-picker-cc v-on:getAddressResultObj="getAddressResultObj"
                       :addressList.sync="addressList">
          <div class="uni-input">{{ addressList.join(' ') }}</div>
        </pca-picker-cc> -->

      </div>
      <div class="margin-top_20rpx">
        <div class="uni-textarea">
          <div class="margin-left_20rpx">

            <el-input class="uni-input "
                      maxlength="11"
                      type="nickname"
                      v-model="logisticsForm.express_phone"
                      placeholder="填写电话号码"></el-input>
          </div>
        </div>
      </div>

      <span slot="footer"
            class="dialog-footer">
        <el-button @click="visibleModalDelivery=false">取 消</el-button>
        <el-button type="primary"
                   @click="visibleModalDeliverFn()">确定</el-button>

      </span>
    </ele-modal>
    <ele-modal width="600px"
               height="300px"
               title="修改地址"
               :visible.sync="visibleModal"
               :maxable="true">
      <!-- class="SigningReminder" -->

      <div class="flex-between padding_20rpx_0 m-bottom15"
           style="border-bottom: 2rpx solid rgb(230, 230, 230);">
        <div class="">
          <el-input class="uni-input"
                    v-model="form.name"
                    placeholder="姓名"></el-input>
        </div>
        <div class="borderLeft">

        </div>
        <div class="margin-left_20rpx">

          <el-input class="uni-input "
                    maxlength="11"
                    type="nickname"
                    v-model="form.phone"
                    placeholder="电话"></el-input>
        </div>
        <div class="margin-left_20rpx">
          <regions-select v-model="city"
                          @input="getAddressResultObj"
                          placeholder="请选择省市区" />
        </div>

      </div>
      <div class="flex-between padding_30rpx_0"
           style="border-bottom: 1px solid rgb(230, 230, 230);">
        <!-- <pca-picker-cc v-on:getAddressResultObj="getAddressResultObj"
                       :addressList.sync="addressList">
          <div class="uni-input">{{ addressList.join(' ') }}</div>
        </pca-picker-cc> -->

      </div>
      <div class="margin-top_20rpx">
        <div class="uni-textarea">
          <el-input v-model="form.address"
                    type="textarea"
                    placeholder-style="color:#999;"
                    :maxlength="150"
                    placeholder="详情地址 (如街道小区 乡镇 村)"></el-input>
        </div>
      </div>

      <span slot="footer"
            class="dialog-footer">
        <el-button @click="visibleModal=false">取 消</el-button>
        <el-button type="primary"
                   @click="visibleModalFn()">确定</el-button>

      </span>
    </ele-modal>
    <!-- 编辑弹窗 -->
    <role-edit :data="currentData"
               :drawerEditBoolen.sync="EditBoolen"
               @done="reload" />
  </div>
</template>
<script>

import RoleEdit from './role-edit';
import { getRegionLabel } from 'ele-admin/packages/utils/regions';
import UserSearch from '../components/user-search.vue';
import moment from 'moment';
import RegionsSelect from '@/components/RegionsSelect/index.vue';
import { goodsOrderList, upAddress, express, confirmReturns } from '@/api/order/goodsOrderList'
import drawerOrderInfo from '../components/drawerOrderInfo.vue';
import { orderTableList } from '../constant/constant';
export default {
  name: 'orderTableList',
  components: { drawerOrderInfo, UserSearch, RegionsSelect, RoleEdit },
  data () {
    return {
      totelPrice: 0,
      toteldisbursementsPrice: 0,
      orderTableList,
      //  技能评分
      colors: ['#99A9BF', '#F7BA2A', '#FF9900'],
      value: 4,
      current: null,
      visibleModal: false,
      visibleModalDelivery: false,
      currTime: new Date().getTime(),
      city: ['140000', '140400', '140425'],
      logisticsForm: {
        // 物流公司
        express_name: '',
        // 物流订单
        express_phone: '',
        // 
        id: ''
      },
      form: {
        province_id: '',
        city_id: '',
        county_id: '',
        province_name: '',
        city_name: '',
        county_name: '',
        address: '',
        id: '',
        name: '',
        phone: ''
      },
      // 表格列配置
      columns: [
        {
          width: 5,
          type: 'expand',
          columnKey: 'expand',
          align: 'center',
          slot: 'expand'
        },
        {
          prop: 'orderingInformation',
          label: '订单信息',
          sortable: 'custom',
          align: 'center',
          showOverflowTooltip: false,
          minWidth: 180,
          slot: 'orderingInformation'
        },

        {
          prop: 'total_price',
          label: '原价',
          sortable: 'custom',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 110,
          slot: 'total_price'
        },
        {
          prop: 'take_over_way',
          label: '配送方式',
          sortable: 'custom',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 110,
          slot: 'take_over_way'
        },
        {
          prop: 'number',
          label: '数量',
          sortable: 'custom',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 150,
          slot: 'number'
        },

        {
          prop: 'pay_way',
          label: '支付方式',
          sortable: 'custom',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 110,
          slot: 'pay_way'
        },
        {
          prop: 'informations',
          label: '信息',
          sortable: 'custom',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 150,
          slot: 'informations'
        },
        {
          prop: 'reality_amount',
          label: '实付款',
          sortable: 'custom',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 150,
          slot: 'reality_amount'
        },
        {
          columnKey: 'action',
          label: '操作',
          minWidth: 150,
          align: 'center',
          resizable: false,
          slot: 'action',
          showOverflowTooltip: false,

        }
      ],
      // 表格选中数据
      selection: [],
      integralName: '',
      drawerEditBoolen: false,
      // 订单列表信息
      orderListInformation: null,
      //  退款说明
      refundInstructions: '',
      orderTableListInfo: null,
      currentData: null,
      EditBoolen: false

    };
  },

  computed: {

    overtimePrice: function () {
      return function (zhuSum, projectList) {
        let sum = '';
        let fitSum = 0;
        for (let i = 0; i < projectList.length; i++) {

          fitSum += Number(projectList[i].plusClockPrice);

        }
        // console.log('fitSum', fitSum);
        sum = Number(zhuSum) + fitSum;
        // console.log(sum)
        return Number(sum).toFixed(2);
      };
    },
    timestamps: function () {
      return function (day) {
        let timestamps = '';
        /* let time = day.split('T')[0] + ' ' + day.split('T')[1];
          timestamps = new Date(time).getTime(); */
        timestamps = new Date(day).getTime();
        timestamps = timestamps + 3600 * 1000 * 1; // 在下单时间的基础上，加一小时
        // console.log('timestamps======', timestamps);
        return timestamps;
      };
    },
    disbursementsPrice () {
      return function (zhuSum, projectList) {
        let sum = '';
        let fitSum = 0;
        for (let i = 0; i < projectList.length; i++) {

          fitSum += Number(projectList[i].plusClockPrice);

        }
        // console.log('fitSum', fitSum);
        sum = Number(zhuSum) + fitSum;
        // console.log(sum)
        return Number(sum).toFixed(2);
      };


    },
    // 卡券余额
    cardCoupon () {
      return function (pointsUsed, deductionAmount) {

        let pointsUseds = pointsUsed ? pointsUsed : 0
        let deductionAmounts = Number(deductionAmount) ? Number(deductionAmount) : 0
        if (deductionAmounts >= pointsUseds) {
          const cardCoupon = deductionAmounts - pointsUseds

          return cardCoupon
        } else {
          return 0
        }
      }
    },
    toDateString () {
      return function (originalDateStr) {
        const date = moment(originalDateStr);
        const formattedDate = date.format('YYYY-MM-DD HH:mm');
        return formattedDate;
      };
    },

    // 是否开启响应式布局
    styleResponsive () {
      return this.$store.state.theme.styleResponsive;
    },
    // 服务状态
    serviceStatusType () {
      return function (serviceType) {

        if (serviceType == 1) {
          return {
            text: '余额支付',
            types: 'success'
          };
        } else if (serviceType == 2) {
          return {
            text: '微信在线支付',
            types: 'success'
          };
        } else if (serviceType == 3) {
          return {
            text: '微信线下充值',
            types: 'success'
          };
        } else if (serviceType == 4) {
          return {
            text: '支付宝充值',
            types: 'success'
          };
        } else if (serviceType == 5) {
          return {
            text: '现金充值',
            types: 'success'
          };
        }
        else if (serviceType == 6) {
          return {
            text: 'pos充值',
            types: 'success'
          };
        }
        else if (serviceType == 7) {
          return {
            text: '微信线上扫码充值',
            types: 'success'
          };
        } else if (serviceType == 8) {
          return {
            text: '支付宝在线扫码充值',
            types: 'success'
          };
        }
      };
    },
    // 服务状态
    // serviceStatusType () {
    //   return function (serviceType) {

    //     if (serviceType == 1) {
    //       return {
    //         status: '已支付',
    //         types: 'success'
    //       };
    //     } else if (serviceType == 2) {
    //       return {
    //         status: '未支付',
    //         types: 'warning'
    //       };
    //     } else if (serviceType == 3) {
    //       return {
    //         status: '退款',
    //         types: 'danger'
    //       };
    //     } else {
    //       return {
    //         status: '状态为null',
    //         types: 'danger'
    //       };
    //     }
    //   };
    // },

    // // 订单状态 status订单状态（3待发货 4.待收货 5已退款 6.已完成 )
    informationType () {
      return function (informationType) {

        if (informationType == 3) {
          return {
            text: '待发货',
            types: 'warning'
          };
        } else if (informationType == 4) {
          return {
            text: '待收货',
            types: 'info'
          };
        } else if (informationType == 5) {
          return {
            text: '退款中',
            types: 'danger'
          };
        } else if (informationType == 6) {
          return {
            text: '已完成',
            types: 'success'
          };
        } else if (informationType == 1) {
          return {
            text: '待付款',
            types: 'success'
          };
        } else if (informationType == 2) {
          return {
            text: '已支付',
            types: 'success'
          };
        } else if (informationType == 7) {
          return {
            text: '已退款',
            types: 'danger'
          };
        } else if (informationType == 8) {
          return {
            text: '已取消',
            types: 'danger'
          };
        }
      };
    }
  },
  activated () {

    this.reload()
  },
  methods: {
    // 同意退款
    async agreeRefund (row) {
      const res = await confirmReturns({
        id: row.id
      })
      if (res.code == 0) {
        this.$message.success(res.msg);

        this.reload();
      }
    },
    visibleModalDeliverFn () {
      if (!this.logisticsForm.express_name) {
        this.$message.error('请填写送货人姓名');

        return false;
      } else if (!this.logisticsForm.express_phone) {

        this.$message.error('请填写联系电话');
        return false;
        // 当前因为省市区/县 是一起的，所以单判断province（省）
      } else {
        const loading = this.$loading({ lock: true });
        this.logisticsForm.id = this.orderTableListInfo.id
        express({ ...this.logisticsForm })
          .then((msg) => {

            loading.close();
            console.log(msg)
            this.$message.success(msg.message);
            this.visibleModalDelivery = false

            this.reload();
          })
          .catch((e) => {
            loading.close();
            this.$message.error(e.message);
          });
      }

    },
    // 打印列表
    openPrintList (row) {
      console.log(row);
      if (row?.id) {
        // const res = await siteCategoriesDetail(row.id);

        this.currentData = row;
        // 用户余额管理
        this.EditBoolen = !this.EditBoolen;
      } else {
        this.EditBoolen = !this.EditBoolen;
        this.currentData = null;
      }
    },
    visibleModalFn () {
      if (!this.form.name) {
        this.$message.error('请填写姓名');

        return false;
      } else if (!/^1[3456789]\d{9}$/.test(this.form.phone)) {
        this.$message.error('请输入正确的手机号');

        return false;
        // 当前因为省市区/县 是一起的，所以单判断province（省）
      } else if (!this.form.province_name) {
        this.$message.error('请选择省市区/县');

        return false;
      } else if (!this.form.address) {
        this.$message.error('请填写详细地址');

        return false;
      } else {
        const loading = this.$loading({ lock: true });
        upAddress({ ...this.form })
          .then((msg) => {

            loading.close();
            console.log(msg)
            this.$message.success(msg.msg);
            this.reload();
            this.visibleModal = false
          })
          .catch((e) => {
            loading.close();
            this.$message.error(e.msg);
          });
      }


    },
    openEdit (row) {
      this.visibleModal = true
      this.orderTableListInfo = row
      console.log()
      this.$util.assignObject(this.form, {
        ...row
      });
      console.log(this.form)

      this.city[0] = String(this.form.province_id)
      this.city[1] = this.form.city_id.toString()
      this.city[2] = this.form.county_id.toString()
      const newArr = this.city.map(str => {
        if (str.length < 6) {
          return str.padEnd(6, '0'); // 使用 padEnd 在字符串末尾补零，直到长度为 6
        } else {
          return str.substring(0, 6); // 只取字符串的前 6 位
        }
      });
      this.city = newArr
      console.log(this.city)
    },
    getAddressResultObj (value, nameCode) {
      console.log(value, nameCode)

      const regionLabel = getRegionLabel(value);
      console.log(regionLabel)
      this.form.city_name = regionLabel[1]
      this.form.city_id = value[1]
      this.form.county_name = regionLabel[2]
      this.form.county_id = value[2]
      this.form.province_name = regionLabel[0]
      this.form.province_id = value[0]
    },
    //  部分退款
    // partialRefund (row) {


    //   console.log(row)
    //   this.orderListInformation = row
    //   this.visibleModal = !this.visibleModal
    //   //refundIst
    // },

    // 点击查看详情弹出详情抽屉
    async divDetail (row) {
      if (row) {
        // const res = await orderDetail(row.id)
        // console.log(res)
        this.current = row;
        // 用户余额管理
        this.drawerEditBoolen = !this.drawerEditBoolen;
      } else {
        this.drawerEditBoolen = !this.drawerEditBoolen;
        this.current = null;
      }
    },

    /* 表格数据源 */

    async datasource ({ page, limit, where }) {

      const res = await goodsOrderList({
        page,
        limit,
        ...where,

      });
      console.log(res)
      res.list.forEach((item) => {
        item.host_img = item.host_img.split(',').map((item) => item.trim());
      })
      return res;
    },
    /* 刷新表格 */
    reload (where) {
      console.log(where)
      this.$refs.table.reload({ page: 1, where: where });
    },

    /* 发货 */
    remove (row) {
      console.log(row)
      this.orderTableListInfo = row
      this.visibleModalDelivery = true
    },
    /* 批量删除 */
    // removeBatch () {
    //   if (!this.selection.length) {
    //     this.$message.error('请至少选择一条数据');
    //     return;
    //   }
    //   this.$confirm('确定要删除选中的套餐吗?', '提示', {
    //     type: 'warning'
    //   })
    //     .then(() => {
    //       const loading = this.$loading({ lock: true });
    //       removeMeal({ ids: this.selection.map((d) => d.id) })
    //         .then((msg) => {
    //           loading.close();
    //           this.$message.success(msg);
    //           this.reload();
    //         })
    //         .catch((e) => {
    //           loading.close();
    //           this.$message.error(e.message);
    //         });
    //     })
    //     .catch(() => { });
    // }
  }
};
</script>
<style lang="less" scoped>
.orderTableList {
  //   /deep/ .el-table__row {
  //     border-bottom: 5px solid rgb(235, 233, 233) !important;
  //   }
  /deep/ .expanded {
    // display: inline-block;
    width: 100%;
    // border-top: 5px solid rgb(235, 233, 233) !important;
    background-color: aliceblue;
  }
  /deep/ .el-table--medium .el-table__cell {
    border: none !important;
  }
  /deep/ .el-icon-arrow-right:before {
    display: none;
  }
  /deep/ .el-textarea__inner {
  }
  .realNameStyle {
    .avaterName {
      width: 74px;
      height: 74px;

      vertical-align: middle;
      margin-right: 5px;
      position: relative;
    }
    .addClock {
      position: absolute;
      top: 10px;

      width: 30px;
      height: 24px;
      background-color: #1890ff;
    }
    .avaterNameAddClock {
      width: 74px;
      height: 74px;

      vertical-align: middle;
      margin-right: 5px;
      position: relative;
    }
    .addClocks {
      position: relative;
      top: -74px;

      width: 30px;
      height: 24px;
      background-color: #1890ff;
    }
    .technicianName {
      color: #1890ff;
      font-size: 12px;
      font-style: normal;
      font-weight: 400;
    }
  }
  .orderrowinfo {
    width: 100%;
    display: flex;
    min-width: 1000px;
    padding: 30px;
    height: 50px;
    align-items: center;
    justify-content: flex-start;
    background-color: #f8f8f8;
    border-bottom: 5px solid rgb(235, 233, 233) !important;
    .orderNumber,
    .createDate,
    .buyName,
    .iphone {
      margin-right: 40px;
      color: #000;
      font-family: Inter;
      font-size: 14px;
      font-style: normal;
      font-weight: 400;
      margin-left: 15px;
    }
  }
}
</style>
